package com.asiainfo.hybridapp.activity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Process;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.asiainfo.hybridapp.R;
import com.asiainfo.hybridapp.configs.ConstantsME;
import com.asiainfo.hybridapp.configs.DebugConfig;
import com.asiainfo.hybridapp.configs.EventBusTag;
import com.asiainfo.hybridapp.configs.InterfaceConfig;
import com.asiainfo.hybridapp.configs.RealInterfaceConfig;
import com.asiainfo.hybridapp.entity.PopulationRankInfo;
import com.asiainfo.hybridapp.fragment.CommonWebviewFragment;
import com.asiainfo.hybridapp.fragment.TBScommonWebviewFragment;
import com.asiainfo.hybridapp.networkModel.HttpUtil;
import com.asiainfo.hybridapp.other.OnRequestListResult_;
import com.asiainfo.hybridapp.utils.ReloginUtil;
import com.framework.customviews.MyRadioGroupForAll;
import com.framework.utils.CollectionUtil;
import com.framework.utils.ScreenUtils;
import com.framework.utils.Y;
import com.framework2.okhttp3.AllCookieJar;
import com.framework2.utils.CookieManagerUtil;
import com.framework2.utils.JsoupUtil;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import custom.org.greenrobot.eventbus.Subscribe;
import custom.org.greenrobot.eventbus.ThreadMode;

public class HomepageActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.overlay)
    FrameLayout overlay;
    @BindView(R.id.relative_center_homepage)
    RelativeLayout relativeCenterHomepage;
    @BindView(R.id.root)
    LinearLayout root;
    @BindView(R.id.rb_1)
    RadioButton rb1;
    @BindView(R.id.rb_2)
    RadioButton rb2;
    @BindView(R.id.rb_3)
    RadioButton rb3;
    @BindView(R.id.rg)
    MyRadioGroupForAll rg;

    private Fragment lastShownFragment;
    private Fragment fragment_1;
    private Fragment fragment_2;
    private Fragment fragment_3;
    private long exitTime;

    //        private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
//            = new BottomNavigationView.OnNavigationItemSelectedListener() {
//
//        @Override
//        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
//            switch (item.getItemId()) {
//                case R.id.navigation_home:
//                    mTextMessage.setText(R.string.title_home);
//                    HttpUtil.getInstance().requestLogin(InterfaceConfig.login, "13901099999", "bj10086", new
//                    HttpUtil.OnRequestResult<String>() {
//                        @Override
//                        public void onSuccess(String... t) {
//                            Y.y("requestLogin_onSuccess:" + t);
//                        }
//
//                        @Override
//                        public void onFail(int code, String msg) {
//                            Y.y("requestLogin_onFail:" + msg);
//                        }
//                    });
//                    return true;
//                case R.id.navigation_dashboard:
//                    mTextMessage.setText(R.string.title_dashboard);
//                    Bundle bundle = new Bundle();
//                    bundle.putString(ConstantsME.url, "http:www.baidu.com");
//                    bundle.putString(ConstantsME.title, "我是网页名字");
//                    startActivity(CommonWebViewActivity.class, bundle);
//                    return true;
//                case R.id.navigation_notifications:
//                    mTextMessage.setText(R.string.title_notifications);
//                    return true;
//            }
//            return false;
//        }
//
//    };
    private void test() {
        CookieManagerUtil.getInstance().synCookies(this, RealInterfaceConfig.getRealBaseServerUrl());
        HttpUtil.getInstance().test(this, InterfaceConfig.webMainList, new HttpUtil.OnRequestResult<String>() {
            @Override
            public void onSuccess(String... t) {
                Y.y("requestLogin_onSuccess:" + t);
            }

            @Override
            public void onFail(int code, String msg) {
                Y.y("requestLogin_onFail:" + msg);
            }
        });
    }

    private void jsCLickLoginTest() {
        CookieManagerUtil.getInstance().synCookies(this, RealInterfaceConfig.getRealBaseServerUrl());
        HttpUtil.getInstance().requestLogin(InterfaceConfig.jsCLickLogin, "13901010085", "bj10086",
                new HttpUtil.OnRequestResult<String>() {
                    @Override
                    public void onSuccess(String... t) {
                        Y.y("requestLogin_onSuccess:" + t);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        Y.y("requestLogin_onFail:" + msg);
                    }
                });
    }

    //eventBus通知 cookieChanged
    @Subscribe(threadMode = ThreadMode.MAIN, tag = EventBusTag.getShopIdSuccess)
    public void webCookieChanged(String cookie) {
        CookieManagerUtil.getInstance().synCookies(this, RealInterfaceConfig.getRealBaseServerUrl());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_homepage_percent);
        ButterKnife.bind(this);
        initCompoundDrawable(0);
        initEvent();
        showFragment(0);
        jsoupData();
//        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
//        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

    private void initCompoundDrawable(int heightAndWidth) {
        Drawable[] compoundDrawables = rb1.getCompoundDrawables();
        compoundDrawables[1].setBounds(0, 0, heightAndWidth > 0 ? (int) (heightAndWidth * 0.44) :
                ScreenUtils.getInstance().dip2px(this, 25), heightAndWidth > 0 ? (int) (heightAndWidth * 0.44) :
                ScreenUtils.getInstance().dip2px(this, 25));
        rb1.setCompoundDrawables(compoundDrawables[0], compoundDrawables[1], compoundDrawables[2],
                compoundDrawables[3]);
        compoundDrawables = rb2.getCompoundDrawables();
        compoundDrawables[1].setBounds(0, heightAndWidth > 0 ? (int) (heightAndWidth * 0.44) * 6 / 44 : 10,
                heightAndWidth > 0 ? (int) (heightAndWidth * 0.44) : ScreenUtils.getInstance().dip2px(this, 25),
                heightAndWidth > 0 ? ((int) (heightAndWidth * 0.44) - (int) (heightAndWidth * 0.44) * 6 / 44) :
                        (ScreenUtils.getInstance().dip2px(this, 25) - 10));
        rb2.setCompoundDrawables(compoundDrawables[0], compoundDrawables[1], compoundDrawables[2],
                compoundDrawables[3]);
        compoundDrawables = rb3.getCompoundDrawables();
        compoundDrawables[1].setBounds(0, heightAndWidth > 0 ? (int) (heightAndWidth * 0.44) * 6 / 44 : 10,
                heightAndWidth > 0 ? (int) (heightAndWidth * 0.44) : ScreenUtils.getInstance().dip2px(this, 25),
                heightAndWidth > 0 ? ((int) (heightAndWidth * 0.44) - (int) (heightAndWidth * 0.44) * 6 / 44) :
                        (ScreenUtils.getInstance().dip2px(this, 25) - 10));
        rb3.setCompoundDrawables(compoundDrawables[0], compoundDrawables[1], compoundDrawables[2],
                compoundDrawables[3]);

        rb1.setCompoundDrawablePadding(heightAndWidth > 0 ? heightAndWidth * 5 / 100 : 20);
        rb2.setCompoundDrawablePadding(heightAndWidth > 0 ? heightAndWidth * 11 / 100 : 40);
        rb3.setCompoundDrawablePadding(heightAndWidth > 0 ? heightAndWidth * 11 / 100 : 40);
    }

    private void initEvent() {
        rg.setOnCheckedChangeListener(new MyRadioGroupForAll.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(MyRadioGroupForAll group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_1:
                        showFragment(0);
//                        test();
//                        jsCLickLoginTest();
                        break;
                    case R.id.rb_2:
                        showFragment(1);
                        break;
                    case R.id.rb_3:
                        showFragment(2);
//                        finish();
//                        ReloginUtil.getInstance().gotoLogin(HomepageActivity.this);
                        break;
                    default:
                        break;
                }
            }
        });
        rg.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (rg.getHeight() > 0) {
                    int a = ScreenUtils.getInstance().getScreenHeightPx(HomepageActivity.this);
                    int b = ScreenUtils.getInstance().getStatusBarHeightPx(HomepageActivity.this);
                    initCompoundDrawable((a - b) * 9 / 100);
                    rg.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
            }
        });
    }

    private void jsoupData() {
        JsoupUtil.getInstance().connectGetTest(RealInterfaceConfig.getRealBaseServerUrl(),
                new AllCookieJar(this).loadForRequest(null), new OnRequestListResult_<PopulationRankInfo>() {

                    @Override
                    public void onSuccess_(List<PopulationRankInfo> list, String... msg) {
                        Y.y("JsoupUtil_onSuccess" + list.size());
                        for (PopulationRankInfo in : list) {
                            Y.y("JsoupUtil_onSuccess:" + in.getTitle());
                        }
                        if (!CollectionUtil.getInstance().isEmpty(list)) {
                        }
                    }

                    @Override
                    public void onFail_(int code, String msg) {
                        if (TextUtils.equals(msg, InterfaceConfig.reLogin)) {
                            ReloginUtil.getInstance().gotoLogin(HomepageActivity.this);
                        }
                        Y.y("JsoupUtil_onFail");
                    }
                });
    }

    private void showFragment(int position) {
        Fragment Center_mContent = null;
        FragmentTransaction ft = getSupportFragmentManager()
                .beginTransaction();
        if (position == 0 && fragment_1 == null) {
//            fragment_1 = new HomepageFragment();
            if (DebugConfig.TBSx5) {
                fragment_1 = new TBScommonWebviewFragment();
            } else {
                fragment_1 = new CommonWebviewFragment();
            }
            Bundle bundle1 = new Bundle();
            bundle1.putString(ConstantsME.url, RealInterfaceConfig.getRealBaseServerUrl()
                    + InterfaceConfig.webMain
            );
            fragment_1.setArguments(bundle1);

            ft.add(R.id.relative_center_homepage, fragment_1);
        } else if (position == 1 && fragment_2 == null) {
            if (DebugConfig.TBSx5) {
                fragment_2 = new TBScommonWebviewFragment();
            } else {
                fragment_2 = new CommonWebviewFragment();
            }
            Bundle bundle2 = new Bundle();
            bundle2.putString(ConstantsME.url, RealInterfaceConfig.getRealBaseServerUrl() + InterfaceConfig.webBanner);
            fragment_2.setArguments(bundle2);
            ft.add(R.id.relative_center_homepage, fragment_2);
        } else if (position == 2 && fragment_3 == null) {
            if (DebugConfig.TBSx5) {
                fragment_3 = new TBScommonWebviewFragment();
            } else {
                fragment_3 = new CommonWebviewFragment();
            }
            Bundle bundle3 = new Bundle();
            bundle3.putString(ConstantsME.url, RealInterfaceConfig.getRealBaseServerUrl() + InterfaceConfig.webSummary);
            fragment_3.setArguments(bundle3);
            ft.add(R.id.relative_center_homepage, fragment_3);
        }
        if (position == 0) {
            Center_mContent = fragment_1;
            tvTitle.setText("北京市朝阳区分局");
        } else if (position == 1) {
            Center_mContent = fragment_2;
            tvTitle.setText("警民互动");
        } else if (position == 2) {
            Center_mContent = fragment_3;
            tvTitle.setText("我的");
        }
        ScreenUtils.getInstance().setTranslucentStatus(this, true);
        ScreenUtils.getInstance().setStatusBarTintColor(this, getResources().getColor(R.color.white));
        if (lastShownFragment != null) {
            ft.hide(lastShownFragment).show(Center_mContent).commit();
        } else {
            ft.show(fragment_1).commit();
        }
        lastShownFragment = Center_mContent;
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - this.exitTime > 2000L) {
                Toast.makeText(this.getApplicationContext(),
                        this.getResources().getString(R.string.exist) + this.getResources().getString(R.string.app_name), Toast.LENGTH_SHORT).show();
                this.exitTime = System.currentTimeMillis();
            } else {
                // 返回主界面
                /**
                 * 退出登录,清空数据
                 */
//                Intent intent_home = new Intent(Intent.ACTION_MAIN);
//                intent_home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                intent_home.addCategory(Intent.CATEGORY_HOME);
//                startActivity(intent_home);
//                finish();
//                System.exit(0);
                ////////////////////
                int pid = Process.myPid();
                Process.killProcess(pid);
            }
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
}
